package com.hdax.dmw.item.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SpringCacheConfig {
    private RedisCacheConfiguration getRedisConfigurationWithTtl(long seconds){
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith(name->name+":")
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .disableCachingNullValues()
                .entryTtl(Duration.ofSeconds(seconds));
        return configuration;
    }

    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory connectionFactory) {
        Map<String,RedisCacheConfiguration> configurationMap = new HashMap<>();
        configurationMap.put("navs",getRedisConfigurationWithTtl(60L * 60 * 24));
        RedisCacheManager cacheManager = RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(connectionFactory)
                .withInitialCacheConfigurations(configurationMap)
                .build();
        return cacheManager;
    }

    @Bean
    public KeyGenerator ruleKeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            //省略生成key规则（业务相关）
            sb.append("index");
            return sb.toString();
        };
    }
}
